class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        //求出前缀乘积和后缀乘积
        int n=nums.size();
        vector<int>pre(n);
        auto back=pre; 
        pre[0]=nums[0];
        back[n-1]=nums[n-1];
        //求前缀乘积
        for(int i=1;i<n;i++){
            pre[i]=pre[i-1]*nums[i];
        }
        //求后缀乘积
        for(int i=n-2;i>=0;i--){
            back[i]=back[i+1]*nums[i];
        }
        vector<int>ret(n);
        for(int i=0;i<n;i++){
            int res=1;
            if(i-1>=0)res*=pre[i-1];
            if(i+1<n)res*=back[i+1];
            ret[i]=res; 
        }
        return ret; 
    }
};